package com.dqhl.community.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.view.PictureHandlePopupWindow;
import com.dqhl.community.view.PictureSelectPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by cheng on 2016/9/8.
 * 创建新档案
 */
public class CreateHealthyFileActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private TextView tvTopOperation;
    private ImageView ivInsertPic;
    private View mainView;

    private PictureSelectPopupWindow pictureSelectPopupWindow; // 照片选择popupwindow
    private PictureHandlePopupWindow pictureHandlePopupWindow;
    private static int REQUESTCODE_PICTURE = 100;
    private static int REQUESTCODE_CAMERA = 101;
    //    private boolean isNullPic = true;//imageview处图片是否为空
    private String imgPath = "";

    private ImageView ivPic1, ivPic2, ivPic3, ivPic4, ivPic5, ivPic6;
    private String pathPic1 = "";
    private String pathPic2 = "";
    private String pathPic3 = "";
    private String pathPic4 = "";
    private String pathPic5 = "";
    private String pathPic6 = "";
    private int countPic = 0;// 添加图片数量  imageview处图片是否为空
    private int TAG = 0;//  标记是那张图片
    private TextView tvHasNum; //剩余可输入多少字
    private EditText etContent;
    private int maxNum = 150; //输入限制的最大字数

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_healthy_file);

        initView();
    }

    private void initView() {
        mainView = findViewById(R.id.activity_create_healthy_file);
        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopTitle.setText("新建档案");
        tvTopOperation = (TextView) findViewById(R.id.tv_top_operation);
        tvTopOperation.setText("发布");
        etContent = (EditText) findViewById(R.id.et_content);
        tvHasNum = (TextView) findViewById(R.id.tv_hasnum);
        tvHasNum.setText("0/" + maxNum);
        etContent.addTextChangedListener(new TextWatcher() {
            CharSequence temp;
            int selectionStart;
            int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                temp = charSequence;
            }

            @Override
            public void afterTextChanged(Editable editable) {
                tvHasNum.setText(editable.length() + "/" + maxNum);
                selectionStart = etContent.getSelectionStart();
                selectionEnd = etContent.getSelectionEnd();
                if (temp.length() > maxNum) {
                    toast("不能超过" + maxNum + "个字");
                    editable.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    etContent.setText(editable);
                    etContent.setSelection(tempSelection); //设置光标在最后
                }
            }
        });

        ivInsertPic = (ImageView) findViewById(R.id.iv_insert_pic);
        ivPic1 = (ImageView) findViewById(R.id.iv_pic_1);
        ivPic2 = (ImageView) findViewById(R.id.iv_pic_2);
        ivPic3 = (ImageView) findViewById(R.id.iv_pic_3);
        ivPic4 = (ImageView) findViewById(R.id.iv_pic_4);
        ivPic5 = (ImageView) findViewById(R.id.iv_pic_5);
        ivPic6 = (ImageView) findViewById(R.id.iv_pic_6);
        ivPic1.setOnClickListener(this);
        ivPic2.setOnClickListener(this);
        ivPic3.setOnClickListener(this);
        ivPic4.setOnClickListener(this);
        ivPic5.setOnClickListener(this);
        ivPic6.setOnClickListener(this);

        ivTopBack.setOnClickListener(this);
        tvTopOperation.setOnClickListener(this);
        ivInsertPic.setOnClickListener(this);

        pictureSelectPopupWindow = new PictureSelectPopupWindow(this, pictureSelectItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });
        pictureHandlePopupWindow = new PictureHandlePopupWindow(this, pictureHandleItemsOnClick);
        pictureHandlePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureHandlePopupWindow.backgroundAlpha(1.0f);
            }
        });
    }

    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, REQUESTCODE_CAMERA);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, REQUESTCODE_PICTURE);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:   // 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };

    View.OnClickListener pictureHandleItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_big_picture:
                    pictureHandlePopupWindow.dismiss();
                    Bundle bundle = new Bundle();
                    if (TAG == 1) {
                        bundle.putString("img_path", pathPic1);
                    } else if (TAG == 2) {
                        bundle.putString("img_path", pathPic2);
                    } else if (TAG == 3) {
                        bundle.putString("img_path", pathPic3);
                    } else if (TAG == 4) {
                        bundle.putString("img_path", pathPic4);
                    } else if (TAG == 5) {
                        bundle.putString("img_path", pathPic5);
                    } else if (TAG == 6) {
                        bundle.putString("img_path", pathPic6);
                    }
                    overlay(ImageShowerActivity.class, bundle);
                    break;
                case R.id.btn_delete: // 删除图片
                    pictureHandlePopupWindow.dismiss();
                    if (TAG == 1) {
                        pathPic1 = "";
                        ivPic1.setVisibility(View.GONE);
                        countPic -= 1;
                    } else if (TAG == 2) {
                        pathPic2 = "";
                        ivPic2.setVisibility(View.GONE);
                        countPic -= 1;
                    } else if (TAG == 3) {
                        pathPic3 = "";
                        ivPic3.setVisibility(View.GONE);
                        countPic -= 1;
                    } else if (TAG == 4) {
                        pathPic4 = "";
                        ivPic4.setVisibility(View.GONE);
                        countPic -= 1;
                    } else if (TAG == 5) {
                        pathPic5 = "";
                        ivPic5.setVisibility(View.GONE);
                        countPic -= 1;
                    } else if (TAG == 6) {
                        pathPic6 = "";
                        ivPic6.setVisibility(View.GONE);
                        countPic -= 1;
                    }
                    ivInsertPic.setVisibility(View.VISIBLE);
                    break;
                case R.id.btn_cancel:
                    pictureHandlePopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.tv_top_operation: //发布
                doSubmit();
                break;
            case R.id.iv_insert_pic:
                pictureSelectPopupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                pictureSelectPopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.iv_pic_1:
                if (!"".equals(pathPic1) && pathPic1.length() > 0) {
                    TAG = 1;
                    pictureHandlePopupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_pic_2:
                if (!"".equals(pathPic2) && pathPic2.length() > 0) {
                    TAG = 2;
                    pictureHandlePopupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_pic_3:
                if (!"".equals(pathPic3) && pathPic3.length() > 0) {
                    TAG = 3;
                    pictureHandlePopupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_pic_4:
                if (!"".equals(pathPic4) && pathPic4.length() > 0) {
                    TAG = 4;
                    pictureHandlePopupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_pic_5:
                if (!"".equals(pathPic5) && pathPic5.length() > 0) {
                    TAG = 5;
                    pictureHandlePopupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_pic_6:
                if (!"".equals(pathPic6) && pathPic6.length() > 0) {
                    TAG = 6;
                    pictureHandlePopupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
        }
    }

    /**
     * 发布
     */
    private void doSubmit() {
        String strContent = etContent.getText().toString();
        if ("".equals(strContent) || strContent.length() <= 0) {
            toast("请输入档案信息");
        } else {
            File pic_a = new File(pathPic1);
            File pic_b = new File(pathPic2);
            File pic_c = new File(pathPic3);
            File pic_d = new File(pathPic4);
            File pic_e = new File(pathPic5);
            File pic_f = new File(pathPic6);

            RequestParams params = new RequestParams(Config.Api.create_healthy_file);
            params.addBodyParameter("id", app.getUserId());
            params.addBodyParameter("info", strContent);
            if (pic_a.isFile()) {
                Dlog.e(pic_a.getPath());
                params.addBodyParameter("pic_a", pic_a);
            }
            if (pic_b.isFile()) {
                Dlog.e(pic_b.getPath());
                params.addBodyParameter("pic_b", pic_b);
            }
            if (pic_c.isFile()) {
                Dlog.e(pic_c.getPath());
                params.addBodyParameter("pic_c", pic_c);
            }
            if (pic_d.isFile()) {
                Dlog.e(pic_d.getPath());
                params.addBodyParameter("pic_d", pic_d);
            }
            if (pic_e.isFile()) {
                Dlog.e(pic_e.getPath());
                params.addBodyParameter("pic_e", pic_e);
            }
            if (pic_f.isFile()) {
                Dlog.e(pic_f.getPath());
                params.addBodyParameter("pic_f", pic_f);
            }
            showCustomLoadBar("发布中……");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 0) {
                        toast("发布成功");
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        toast("发布失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == REQUESTCODE_PICTURE && resultCode == RESULT_OK) {
                Uri selectedImage = geturi(data);
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                if (c != null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String picturePath = c.getString(columnIndex);
                    Dlog.e("picturePath=========" + picturePath);
                    c.close();
                    setImage(picturePath);
                }
            }
            if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK) {
                String sdState = Environment.getExternalStorageState();
                if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                    Dlog.e("sd card unmount");
                }
                String name = UUID.randomUUID().toString() + ".jpg";
                File file = new File("/sdcard/pintu");
                file.mkdirs();
                Bundle bundle = data.getExtras();
                //获取相机返回的数据，并转换为图片格式
                Bitmap bitmap = (Bitmap) bundle.get("data");
                FileOutputStream fout = null;
                String fileName = file.getPath() + name;
                try {
                    fout = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    setImage(fileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fout != null) {
                            fout.flush();
                            fout.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void setImage(String path) {
        if ("".equals(pathPic1) && pathPic1.length() == 0) {
            pathPic1 = path;
            ivPic1.setVisibility(View.VISIBLE);
            x.image().bind(ivPic1, pathPic1);
            countPic += 1;
        } else if ("".equals(pathPic2) && pathPic2.length() == 0) {
            pathPic2 = path;
            ivPic2.setVisibility(View.VISIBLE);
            ivPic2.setVisibility(View.VISIBLE);
            x.image().bind(ivPic2, pathPic2);
            countPic += 1;
        } else if ("".equals(pathPic3) && pathPic3.length() == 0) {
            pathPic3 = path;
            ivPic3.setVisibility(View.VISIBLE);
            ivPic3.setVisibility(View.VISIBLE);
            x.image().bind(ivPic3, pathPic3);
            countPic += 1;
        } else if ("".equals(pathPic4) && pathPic4.length() == 0) {
            pathPic4 = path;
            ivPic4.setVisibility(View.VISIBLE);
            ivPic4.setVisibility(View.VISIBLE);
            x.image().bind(ivPic4, pathPic4);
            countPic += 1;
        } else if ("".equals(pathPic5) && pathPic5.length() == 0) {
            pathPic5 = path;
            ivPic5.setVisibility(View.VISIBLE);
            ivPic5.setVisibility(View.VISIBLE);
            x.image().bind(ivPic5, pathPic5);
            countPic += 1;
        } else if ("".equals(pathPic6) && pathPic6.length() == 0) {
            pathPic6 = path;
            ivPic6.setVisibility(View.VISIBLE);
            ivPic6.setVisibility(View.VISIBLE);
            x.image().bind(ivPic6, pathPic6);
            ivInsertPic.setVisibility(View.GONE);
            countPic += 1;
        }
    }

    /**
     * 解决小米部分手机调用系统相册失败
     *
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri.parse("content://media/external/images/media/" + index);
                    if (uri_temp != null) {
                        Dlog.e("uri_temp:" + uri_temp.toString());
                        uri = uri_temp;
                    }
                }
            }
        }
        Dlog.e("uri:" + uri.toString());
        return uri;
    }
}
